﻿using System;
using System.Web.UI.WebControls;

using EBAYVN.Util ;
using ETRANPORT.Domain;
using ETRANPORT.Web.Common;
using EBAYVN.Dao;
using ETRANPORT.Web.Shared;
using ETRANPORT.Web.UserControls;
using System.Collections.Generic;


namespace ETRANPORT.Web.Forms.DanhMuc
{
    public partial class PhuongTien : Authentication
    {
        private PhuongTienDao _ptDao = new PhuongTienDao();



        private Mode UpdateMode
        {
            get
            {
                try
                {
                    if (Session[SessionKey.MODE] != null)
                    {
                        var mode = Convert.ToInt32(Session[SessionKey.MODE]);
                        return (mode == Mode.Update.GetHashCode()) ? Mode.Update : Mode.Create;
                    }

                    return Mode.Create;
                }
                catch (Exception)
                {
                    return Mode.Create;
                }
            }

            set
            {
                Session[SessionKey.MODE] = value.GetHashCode();
            }
        }

        private FilteredMode Filtered
        {
            get
            {
                try
                {
                    if (Session[SessionKey.FILTEREDMODE] != null)
                    {
                        var mode = Convert.ToInt32(Session[SessionKey.FILTEREDMODE]);
                        return (mode == FilteredMode.Filtered.GetHashCode()) ? FilteredMode.Filtered : FilteredMode.None;
                    }

                    return FilteredMode.None;
                }
                catch (Exception)
                {
                    return FilteredMode.None;
                }
            }

            set
            {
                Session[SessionKey.FILTEREDMODE] = value.GetHashCode();
            }
        }

        private PHUONGTIEN ItemObj
        {
            get
            {
                if (!ValidateData())
                    return null;

                var obj = new PHUONGTIEN
                             {
                                 MAPT = txtMaPT.Text.Trim(),
                                 TENPT =  txtTenPT.Text.Trim(),
                                 MOTA=txtMoTa.Text.Trim(),
                                 TAITRONGMAX=Decimal.Parse(txtTaiTrongMax.Text.Trim()),
                                 NAMSX=int.Parse(txtNamSX.Text.Trim()),
                                 SOCONTAINERMAX=int.Parse(txtSoLuongConMax.Text.Trim())
                             };

                if (!ddlMaLPT.SelectedValue.Equals("%"))
                    obj.MALPT = ddlMaLPT.SelectedValue;
                if (!ddlMaNSX.SelectedValue.Equals("%"))
                    obj.NHASX = ddlMaNSX.SelectedValue;
                return obj;
            }
        }




        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                
                if (!Page.IsPostBack)
                {
                    // Bind data for grid view
                    LoadStaticReferences();
                    BindDataForGrid();
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        

        #region Startup script registeration
        private void SetControlValue(string id, string value)
        {
            ((EOS)Page.Master).SetControlValue(id, value);
        }

        private void SetReadonly(string id, bool isReadonly)
        {
            ((EOS)Page.Master).SetReadonly(id, isReadonly);
        }

        private void ShowError(string message, string controlId)
        {
            ((EOS)Page.Master).ShowError(message, controlId);
        }

        private void ShowError(string message)
        {
            ((EOS)Page.Master).ShowError(message);
        }

        private void ShowInfor(string message)
        {
            ((EOS)Page.Master).ShowInfor(message);
        }

        private void CloseWaitingDialog()
        {
            ((EOS)Page.Master).CloseWaitingDialog();
        }
        #endregion



        
        private void BindDataForGrid()
        {
            if (Filtered == FilteredMode.None)
            {
                var objList = _ptDao.GetList();

                gvList.DataSource = objList;
                gvList.PagerInforText = objList.Count.ToString();
                gvList.DataBind();
            }
            else
            {
                int? SoCon = null;
                if(!String.IsNullOrEmpty(txtSoLuongConMax.Text.Trim()))
                    SoCon=ConvertUtil.ToInteger(txtSoLuongConMax.Text.Trim());
                Decimal? TaiTrong=null;
                if (!String.IsNullOrEmpty(txtTaiTrongMax.Text.Trim()))
                {
                     TaiTrong= Decimal.Parse(txtTaiTrongMax.Text.Trim());
                }
                var objList = _ptDao.GetList(txtMaPT.Text.Trim(), txtTenPT.Text.Trim(), txtMoTa.Text.Trim(), TaiTrong, ddlMaNSX.SelectedValue, ddlMaLPT.SelectedValue, SoCon);

                gvList.DataSource = objList;
                gvList.PagerInforText = objList.Count.ToString();
                gvList.DataBind();
            }
        }
        
        private void LoadStaticReferences()
        {
            CommonFunc.BindDropDownList(ddlMaLPT, new LoaiPhuongTienDao().GetList(), "TENLPT", "MALPT", true);
            CommonFunc.BindDropDownList(ddlMaNSX, new NhaSXDao().GetList(), "TENNSX", "MANSX", true);
        }

        private bool ValidateData()
        {
            if (string.Empty.Equals(txtMaPT.Text))
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Mã phương tiện"), txtMaPT.ClientID);
                return false;
            }

            if (string.Empty.Equals(txtTenPT.Text))
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Tên phương tiện"), txtTenPT.ClientID);
                return false;
            }
            if (!string.IsNullOrEmpty(txtTaiTrongMax.Text.Trim()))
            {
                try
                {
                    decimal.Parse(txtTaiTrongMax.Text.Trim());
                }
                catch
                {
                    ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Tải trọng tối đa"), txtTaiTrongMax.ClientID);
                    return false;
                }
            }
            
            return true;
        }

        private void ClearForm()
        {
            UpdateMode = Mode.Create;

            txtMaPT.Text = "";
            txtMoTa.Text = "";
            txtTenPT.Text = "";
            txtTaiTrongMax.Text = "1000";
            txtSoLuongConMax.Text = "20";
            txtNamSX.Text = DateTime.Now.Year.ToString();
            
        }

        


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Filtered = FilteredMode.None;
            ClearForm();
            BindDataForGrid();
            upnlGrid.Update();
            CloseWaitingDialog();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var nv = ItemObj;
            if (nv == null)
            {
                CloseWaitingDialog();
                return;
            }

            Message msg;
            Filtered = FilteredMode.None;

            // insert new
            if (UpdateMode == Mode.Create)
            {
                if (!HasInsertPermission)
                {
                    CloseWaitingDialog();
                    ShowInfor(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                var tontai = _ptDao.Get(txtMaPT.Text.Trim());
                if (tontai != null)
                {
                    CloseWaitingDialog();
                    ShowError("Mã phương tiện đã tồn tại", txtMaPT.ClientID);
                    return;
                }

                msg = _ptDao.Insert(nv);
            }
            else
            {
                if (!HasUpdatePermission)
                {
                    CloseWaitingDialog();
                    ShowInfor(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }
                
                msg = _ptDao.Update(nv,0);
            }

            CloseWaitingDialog();

            if (msg == null) return;

            if (msg.MsgType != MessageType.Error)
            {
                ShowInfor(ResourceLabel.Get(msg));

                ClearForm();
                BindDataForGrid();

                upnlGrid.Update();
            }
            else
            {
                ShowError(ResourceLabel.Get(msg));
            }
        }
        protected void btnSaveFix_Click(object sender, EventArgs e)
        {
            var nv = ItemObj;
            if (nv == null)
            {
                CloseWaitingDialog();
                return;
            }

            Message msg;
            Filtered = FilteredMode.None;

            // insert new
            if (UpdateMode == Mode.Create)
            {
                if (!HasInsertPermission)
                {
                    CloseWaitingDialog();
                    ShowInfor(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                var tontai = _ptDao.Get(txtMaPT.Text.Trim());
                if (tontai != null)
                {
                    CloseWaitingDialog();
                    ShowError("Mã phương tiện đã tồn tại", txtMaPT.ClientID);
                    return;
                }

                msg = _ptDao.Insert(nv);
            }
            else
            {
                if (!HasUpdatePermission)
                {
                    CloseWaitingDialog();
                    ShowInfor(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                msg = _ptDao.Update(nv,1);
            }

            CloseWaitingDialog();

            if (msg == null) return;

            if (msg.MsgType != MessageType.Error)
            {
                ShowInfor(ResourceLabel.Get(msg));

                ClearForm();
                BindDataForGrid();

                upnlGrid.Update();
            }
            else
            {
                ShowError(ResourceLabel.Get(msg));
            }
        }
        
        protected void btnFilter_Click(object sender, EventArgs e)
        {
            Filtered = FilteredMode.Filtered;
            BindDataForGrid();
            upnlGrid.Update();
            CloseWaitingDialog();
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                // Authenticate
                if (!HasDeletePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }
                var strIds = Request["listIds"];
                if ((strIds != null) && (!string.Empty.Equals(strIds)))
                {
                    var listIds = strIds.Split(',');

                    // Kiem tra relation ship truoc khi delete
                    string flag = "";
                    foreach (var ma in listIds)
                    {
                        if (_ptDao.IsInUse(ma))
                        {
                            var msgIsInUse = new Message(MessageConstants.E_OBJECT_IN_USED, MessageType.Info, "phương tiện với mã", ma);
                            ShowError(ResourceLabel.Get(msgIsInUse));
                            CloseWaitingDialog();
                            return;
                        }
                        var nv = _ptDao.Get(ma);
                        if (nv != null)
                        {
                            var msg = _ptDao.Delete(nv);
                            if (msg.MsgType == MessageType.Error)
                            {
                                flag += msg.ToString();
                                break;
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(flag))
                    {
                        ShowInfor("Xóa phương tiện thành Công");
                    }
                    else
                    {
                        ShowError(flag);
                    }
                }
                BindDataForGrid();
                upnlGrid.Update();
                CloseWaitingDialog();

            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }




        private void BindItem(PHUONGTIEN obj)
        {
            if (obj == null)
                return;

            SetControlValue(txtMaPT.ClientID, obj.MAPT);
            SetReadonly(txtMaPT.ClientID, true);
            SetControlValue(txtTenPT.ClientID, obj.TENPT);
            var lpt = ddlMaLPT.Items.FindByValue(obj.MALPT);
            if (lpt != null)
                ddlMaLPT.SelectedIndex = ddlMaLPT.Items.IndexOf(lpt);
            var nsx = ddlMaNSX.Items.FindByValue(obj.NHASX);
            if (nsx != null)
                ddlMaNSX.SelectedIndex = ddlMaNSX.Items.IndexOf(nsx);
            
            SetControlValue(txtSoLuongConMax.ClientID, obj.SOCONTAINERMAX.HasValue?obj.SOCONTAINERMAX.Value.ToString():"0");
            SetControlValue(txtTaiTrongMax.ClientID, obj.TAITRONGMAX.HasValue ?obj.TAITRONGMAX.Value.ToString():"0");
            SetControlValue(txtMoTa.ClientID, obj.MOTA);
            SetControlValue(txtNamSX.ClientID, obj.NAMSX.HasValue?obj.NAMSX.Value.ToString():"1990");
            upnlInfor.Update();
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var id = e.CommandArgument.ToString();

                switch (e.CommandName)
                {
                    case "EditItem":
                        var objDb = _ptDao.Get(id);

                        if(objDb != null)
                        {
                            BindItem(objDb);
                            UpdateMode = Mode.Update;
                        }

                        CloseWaitingDialog();

                        break;
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }
    }
}